var partialTitle = "";

$(document).ready(function(){
    $("#category_list").cleanWhitespace();
    $("#ingredient_list").cleanWhitespace();
    
    $('input').keyup(changeMade);
    $('select').change(changeMade);
    $('textarea').keyup(changeMade);
    
    $('#cancel_button').click(function(){
        window.location = getBaseURL()+'meal_editing/edit_meals';
    });
    
    $(".warning_section").hide();
    
    $("#meal_title").keyup(function(){
        checkTitle($("#meal_title").val(),$('#meal_id').val());
    });
    
    $('select#category_options').change(function(){
        if ($(this).val() != -1){
            addItemToListbox($("#category_options"), $("#category_list"));
            $(this).val(-1);
        }
    });
    
    $("#meal_ingredients").keyup(function(event){
        //Prevent updating since form is clearing
        if (event.keyCode != 13){
            partialTitle = $.trim($(this).val());
        }
    })
    
    $("#meal_ingredients").focus(function(){
        $(this).val("");
    })
    
    $("#meal_ingredients").autocomplete({
        source: function( request, response ) {
            $.post(getBaseURL()+"meal_editing/create_meal/searchIngredients/", 
            {request_string: ""+request.term+""},
            function(data){
                response(data);
            }, "json");
        },
        minLength: 1,
        dataType: "json",
        cache: "false",
        select: function(event,ui){
            if (ui.item.label  > 0){
                addIngredient(ui.item);
            }
            else{
                addFancybox("#create_button");
                $("#create_button").click();
            }
            
            return false;
        },
        close: function(event,ui){
            $("#meal_ingredients").val("");
        },
        change: function(event, ui){
            $("#meal_ingredients").val("");
        },
        focus: function(){return false;}
    })
    .on("focus",function () {
            $(this).autocomplete("search", '');
    }).data( "autocomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( "<a>" + item.value + "</a>" )
                .appendTo( ul );
    };
    
    $("#create_meal").click(function(){
        postMeal();
    });
    
    addFancybox("#create_ingredient");
});

function addIngredient(ingr){
    var exists = false;
    $("#ingredient_list .listboxItem").each(function(){
        if ($(this).attr('value') == ingr.label){
            exists = true;
            return false;
        }
    });
    if (!exists){
        $("#ingredient_list").append(createListboxItem(ingr.label, ingr.value));
    }
}

function postMeal(){
    var meal_title = $("#meal_title").val();
    var meal_id = $("#meal_id").val();
    var categories = [];
    var ingredients = [];
    var description = $("#meal_description").val();
    $("#category_list  .listboxItem").each(function(){
        categories.push($(this).attr('value'));     //id value
    });
    $("#ingredient_list .listboxItem").each(function(){
        ingredients.push($(this).attr('value'));    //id value
    });
    
    $.post(getBaseURL()+"meal_editing/create_meal/postMeal/",{
        meal_title: meal_title,
        meal_id: meal_id,
        categories: categories,
        ingredients: ingredients,
        description: description
    },
    function(data){
        if (data == "good"){
            saveMade();
            window.location = getBaseURL()+"meal_editing/edit_meals/";
        }
        if (data == "today"){
            saveMade();
            window.location = getBaseURL()+"meal_editing/edit_meals/";
        }
        else if (data == "server"){
            saveMade();
            window.location = getBaseURL()+"meal_editing/edit_meals/";
        }
        else{
            var responses = new Object();
            if (data.title) {
                responses["#meal_title_section"] = data.title;
            }
            
            if (data.categories){
                responses["#category_section"] = data.categories;
            }
            
            if (data.ingredients){
                responses["#ingredient_section"] = data.ingredients;
            }
            
            highlightSections(responses);
        }
    },"json");

}

function checkTitle(meal_title, meal_id){
    $.post(getBaseURL()+"meal_editing/create_meal/checkTitle/",{
        meal_title: meal_title,
        meal_id: meal_id
    },
    function(data){
        var text = 'Not Unique';
        if (data == "good"){
            text = null;
        }
        toggleHighlight('#meal_title_section', text);
    });
}

function changeMadeReload(ingredient_title){
    $.fancybox.close();
    if (ingredient_title != null){
        $.post(getBaseURL()+"meal_editing/create_meal/getIngredient",{
            ingredient_title: ingredient_title
        }, function(data){
            if (data != "fail"){
                $("#ingredient_list").append(createListboxItem(data, ingredient_title));
            }
        });
    }
}

function getPartialTitle(){
    return partialTitle;
}